package com.mingtu.jgspatrol.activity;

import static com.mingtu.jgspatrol.utils.MyConstant.MAX_ZOOM;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.RadioGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.ServiceSettings;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.SPStaticUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.luck.picture.lib.entity.LocalMedia;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.interfaces.OnConfirmListener;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseApplication;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.utils.ActivityUtil;
import com.mingtu.common.utils.Constant;
import com.mingtu.common.utils.MyLogUtil;
import com.mingtu.common.utils.MyUtills;
import com.mingtu.common.utils.SPTools;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.base.Application;
import com.mingtu.jgspatrol.base.MyBaseActivity;
import com.mingtu.jgspatrol.databinding.ActivitySignInBinding;
import com.mingtu.jgspatrol.room.SignInEvent;
import com.mingtu.jgspatrol.room.SignInEventDao;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

public class SignInActivity extends MyBaseActivity<ActivitySignInBinding> {
    private String address;
    private String lat;
    private String lng;
    private String editContent;
    private List<Marker> markers = new ArrayList<>();
    private ArrayList<HashMap<String, Object>> mylist = new ArrayList<>();
    private int totalTextCount = 100;
    private AMap aMap;
    private int textNum = 0;
    private List<LocalMedia> localMediaList;
    private List<HashMap<String, String>> hashMapList = new ArrayList<>(); //存储要上报的图片、视频的信息
    private boolean netWorkState = true;
    private SignInEventDao signInEventDao;
    private OkHttpClient.Builder builder;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_sign_in;
    }

    @Override
    protected void initView() {
        setModuleTitle("签到");
        setTitleBarBackground(getResources().getDrawable(com.mingtu.home.R.drawable.line_bottom));

        binding.editDescribe.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                textNum -= count;
                binding.tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textNum += count;
                binding.tvTotalTextCount.setText(textNum + "");
            }

            @Override
            public void afterTextChanged(Editable s) {
                MyLogUtil.e("MyTest", "afterTextChanged==" + s.toString());
                String str = MyUtills.getEditText(binding.editDescribe);
                binding.editDescribe.setSelection(str.length());
            }
        });

        int screenWidth = ScreenUtils.getScreenWidth();
        int itemWidth = (screenWidth - SizeUtils.dp2px(5) * 2 - SizeUtils.dp2px(15) * 4) / 3;
        binding.reportPictureVideo.setItemWidth(itemWidth);

    }


    @Override
    protected void initData() {
        address = SPStaticUtils.getString(SPTools.address);
        lat = SPStaticUtils.getString(SPTools.lat);
        lng = SPStaticUtils.getString(SPTools.lng);

        if (!StringUtils.isEmpty(address)) {
            binding.tvAddress.setText(address);
        } else {
            //只有GPS定位的时候，addredd为空，这个时候需要逆地址解析出地址
            if (!StringUtils.isEmpty(lng) && !StringUtils.isEmpty(lat)) {
                ServiceSettings.updatePrivacyShow(context, true, true);
                ServiceSettings.updatePrivacyAgree(context, true);
                try {
                    GeocodeSearch geocoderSearch = new GeocodeSearch(context);
                    geocoderSearch.setOnGeocodeSearchListener(new GeocodeSearch.OnGeocodeSearchListener() {
                        @Override
                        public void onGeocodeSearched(GeocodeResult result, int rCode) {

                        }

                        @Override
                        public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
                            MyLogUtil.e("formatAddress", "rCode:" + rCode);
                            if (rCode == AMapException.CODE_AMAP_SUCCESS) {
                                if (result != null && result.getRegeocodeAddress() != null && result.getRegeocodeAddress().getFormatAddress() != null) {
                                    String formatAddress = result.getRegeocodeAddress().getFormatAddress();
                                    MyLogUtil.e("formatAddress", "formatAddress:" + formatAddress);
                                    address = formatAddress;
                                    binding.tvAddress.setText(formatAddress);
                                }
                            }
                        }
                    });
                    LatLonPoint lp = new LatLonPoint(Double.parseDouble(lat), Double.parseDouble(lng));
                    RegeocodeQuery query = new RegeocodeQuery(lp, 200, GeocodeSearch.AMAP);
                    geocoderSearch.getFromLocationAsyn(query);
                } catch (AMapException e) {
                    e.printStackTrace();
                }

            }
        }


        signInEventDao = Application.getApplication().getSignInEventDao();

        addClickListener(this, binding.butSubmit);

    }

    @Override
    protected void initMap(Bundle savedInstanceState) {
        super.initMap(savedInstanceState);
        binding.mapView.onCreate(savedInstanceState);
        aMap = binding.mapView.getMap();
        //地图模式可选类型：MAP_TYPE_NORMAL,MAP_TYPE_SATELLITE,MAP_TYPE_NIGHT
        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
        aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
        aMap.getUiSettings().setZoomControlsEnabled(false);
        aMap.setMaxZoomLevel(MAX_ZOOM);
        aMap.moveCamera(CameraUpdateFactory.zoomTo(Constant.MAP_ZOOM_TWO));
        binding.radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_map1:
                        aMap.setMapType(AMap.MAP_TYPE_NORMAL);// 矢量地图模式
                        break;
                    case R.id.rb_map2:
                        aMap.setMapType(AMap.MAP_TYPE_SATELLITE);// 矢量地图模式
                        break;
                }
            }
        });

        String longitude = SPStaticUtils.getString(SPTools.lng);
        String latitude = SPStaticUtils.getString(SPTools.lat);
        if (!StringUtils.isEmpty(longitude) && !StringUtils.isEmpty(latitude)) {
            LatLng location = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude));
            //添加Marker
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(location)
                    .icon(BitmapDescriptorFactory.fromResource(com.mingtu.home.R.mipmap.sb_icon_wz));
            Marker marker = aMap.addMarker(markerOptions);
            markers.add(marker);
            aMap.moveCamera(CameraUpdateFactory.changeLatLng(location));
        }
    }

    @Override
    protected void getData() {

    }

    @Override
    public void onNetChange(boolean netWorkState) {
        super.onNetChange(netWorkState);
        this.netWorkState = netWorkState;
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        try {
            //销毁地图对象
            if (aMap != null) {
                binding.mapView.onDestroy();
            }

            for (Marker marker : markers) {
                marker.remove();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.but_submit:
                KeyboardUtils.hideSoftInput(SignInActivity.this);
                //提交操作
                editContent = MyUtills.getEditText(binding.editDescribe);


                hashMapList = binding.reportPictureVideo.getHashMapList();
                List<LinkedHashMap<String, Object>> picVideoUrl = binding.reportPictureVideo.getPicVideoUrl();

                if (hashMapList.size() == 0) {
                    ToastUtils.showLong("请上传视频、图片相关文件！");
                    return;
                }


                localMediaList = binding.reportPictureVideo.getLocalMedisList();

                for (int i = 0; i < picVideoUrl.size(); i++) {
                    LinkedHashMap<String, Object> hashMap = picVideoUrl.get(i);
                    mylist.add(hashMap);
                }

                signInEvent();
                break;

        }
    }


    /**
     * 签到事件
     */
    private void signInEvent() {
        binding.butSubmit.setEnabled(false);
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("lnglat", lng + "," + lat);
        hashMap.put("content", editContent);
        hashMap.put("taskClockAttachVOList", mylist);
        hashMap.put("clockTime", TimeUtils.getNowString());
        String str = GsonUtils.toJson(hashMap);

        //未联网或者mylist中的数据个数和localMediaList中的数据个数不一致的时候（此时说明有部分文件因为网络原因没有生成链接）
        if (!netWorkState || mylist.size() != localMediaList.size()) {
            //没有网络的时候将提交内容存起来,并添加创建时间,提交前判断是否有待上报的信息
            saveSignInEventData(str);
            return;
        }

        builder = new OkHttpClient.Builder();
        builder.addInterceptor(BaseApplication.getHttpLoggingInterceptor());
        builder.readTimeout(3 * 1000, TimeUnit.MILLISECONDS);      //读取超时时间
        builder.writeTimeout(3 * 1000, TimeUnit.MILLISECONDS);     //写入超时时间
        builder.connectTimeout(3 * 1000, TimeUnit.MILLISECONDS);   //连接超时时间

        OkGo.<String>post(MyConstant.POST_CLOCK_TASK)
                .tag(this)
                .upJson(str)
                .client(builder.build())
                .retryCount(1)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            JSONObject jsonObject = JSON.parseObject(result);
                            String success = jsonObject.getString("success");
                            if (success.indexOf("ok") != -1) {
                                ToastUtils.showLong("签到成功！");
                                binding.butSubmit.setEnabled(true);
                                //实例化Timer类 ,守护线程，不在后台一直运行
//                                EventBus.getDefault().post(new MyEventBus(MyConstant.REFRESH_REPORTED_DATA));
                                ActivityUtil.removeActivity(SignInActivity.this);
                            }
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        String result = response.body();
                        MyLogUtil.e(getClass().getSimpleName(), "onError==" + result);
                        binding.butSubmit.setEnabled(true);
                        saveSignInEventData(str);
                    }
                });
    }


    /**
     * 显示提示信息
     */
    private void showPopup(final String str, SignInEvent signInEvent) {
        binding.butSubmit.setEnabled(true);
        BasePopupView popupView = new XPopup.Builder(this)
                .isDestroyOnDismiss(false)
                .dismissOnTouchOutside(false)
                .hasShadowBg(true)
                .asConfirm(context.getResources().getString(R.string.text_tip), "网络不好，签到内容是否保存到本地？",
                        context.getResources().getString(R.string.text_cancle), context.getResources().getString(R.string.text_sure),
                        new OnConfirmListener() {
                            @Override
                            public void onConfirm() {
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        signInEventDao.insertEvent(signInEvent);
                                        ActivityUtil.removeActivity(SignInActivity.this);
                                    }
                                }).start();

                            }
                        }, null, false);
        popupView.show();

    }

    /**
     * 保存上报事件数据
     */
    private void saveSignInEventData(String str) {
        SignInEvent signInEvent = new SignInEvent();
        signInEvent.setLat(lat);
        signInEvent.setLng(lng);
        signInEvent.setContent(editContent);
        signInEvent.setClockTime(TimeUtils.getNowString());

        List<SignInEvent.AttachVOSBean> attachVOS = new ArrayList<>();
        for (int i = 0; i < mylist.size(); i++) {
            HashMap<String, Object> myHashMap = mylist.get(i);
            String url = (String) myHashMap.get("url");
            SignInEvent.AttachVOSBean attachVOSBean = new SignInEvent.AttachVOSBean();
            attachVOSBean.setUrl(url);
            attachVOS.add(attachVOSBean);
        }
        signInEvent.setAttachVOS(attachVOS);

        List<SignInEvent.MyattachVOSBean> myattachVOSBeans = new ArrayList<>();
        for (int i = 0; i < hashMapList.size(); i++) {
            HashMap<String, String> myHashMap = hashMapList.get(i);
            String pathName = (String) myHashMap.get("pathName");
            SignInEvent.MyattachVOSBean myattachVOSBean = new SignInEvent.MyattachVOSBean();
            myattachVOSBean.setPathName(pathName);
            myattachVOSBeans.add(myattachVOSBean);
        }
        signInEvent.setMyattachVOS(myattachVOSBeans);

        showPopup(str, signInEvent);
    }
}